package queuedemo;

/**
 * Created with IntelliJ IDEA
 * Description:  队列的模拟实现
 * User: SEKI TOMOKI
 * Date: 2024-08-03
 * Time: 17:57
 */
public class MyLinkQueue<E> {
    //双向链表的节点
    public static class ListNode<E> {
        private ListNode next;
        private ListNode prev;
        private E elem;

        public ListNode(E elem) {
            this.elem = elem;
        }
    }

    //节点个数
    private int usedSize;
    //头节点的位置
    private ListNode head;
    //尾节点的位置
    private ListNode tail;


    //入队列
    public <E> boolean offer(E elem) {
        if(isEmpty()) {
            head = new ListNode(elem);
            tail = head;
        }else {
            //入队从队尾入
            ListNode node = new ListNode(elem);
            node.prev = this.tail;
            tail.next = node;
            tail = tail.next;
        }
        usedSize++;
        return true;
    }

    //出队列
    public <E> E poll() {
        if(isEmpty()) {
            throw new QueueIsEmptyException("该队列是空的");
        }else {
            //出队列从队头出
            E ret = (E) head.elem;
            head = head.next;
            head.prev = null;
            usedSize--;
            return ret;
        }
    }

    //获取对头元素
    public <E> E peek() {
        if(isEmpty()) {
            throw new QueueIsEmptyException("该队列是空的");
        }else {
            return (E) head.elem;
        }

    }

    //获取队列中有效元素个数
    public int size() {
        return  this.usedSize;
    }

    //检测队列是否为空
    public boolean isEmpty() {
        return size() == 0;
    }

}
